package com.zyh.controller;

import com.zyh.entity.Student;
import com.zyh.entity.Users;
import com.zyh.service.StudentService;
import com.zyh.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class LoginController {
//    @RequestMapping(value = "/login")
//    public String login(){
//        return "/login";
//    }
//    @RequestMapping(value = "/workerHome/")
//    public String checkUser(){
//        return "workerHome";
//    }
    @Resource
    UserService userService;
    @Resource
    StudentService studentService;
    @RequestMapping("/")
    public String home(){
        return "home";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/adminLogin")
    public String adminLogin(Authentication authentication, Model model){

        model.addAttribute("username",authentication.getName());
        return "adminView/adminHome";
    }

    @PreAuthorize("hasRole('WORKER')")
    @RequestMapping("/workerLogin")
    public String workerLogin(Authentication authentication,Model model){
        Users users= userService.findByUserName(authentication.getName());
        model.addAttribute("users",users);
        return "workerView/workerHome";
    }

    @PreAuthorize("hasRole('INSPECTOR')")
    @RequestMapping("/inspectorLogin")
    public String inspectorLogin(Authentication authentication,Model model){
        Users users= userService.findByUserName(authentication.getName());
        model.addAttribute("users",users);
        return "InspectorView/inspectorHome";
    }

    @PreAuthorize("hasRole('STUDENT')")
    @RequestMapping("/studentLogin")
    public String studentLogin(Authentication authentication, Model model){
        Users users= userService.findByUserName(authentication.getName());
        if(isNumeric(users.getUsername())){
            Student student=studentService.findStudentBySno(Integer.parseInt(users.getUsername()));
            model.addAttribute("student",student);
            return "studentView/studentHome";
        }else{
            return "studentView/error";
        }


    }
    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "jsp/login";
    }
}
